
package io.netty.util.internal;

import io.netty.util.concurrent.FastThreadLocal;
import io.netty.util.concurrent.FastThreadLocalThread;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.WeakHashMap;

//注意当前类继承了UnpaddedInternalThreadLocalMap，所以拥有父类的一些属性
//这个ThreadLocal是为了让普通的Thread也可以使用FastThreadLocal，
//虽然性能没有配合FastThreadLocalThread那么高效，但是也比普通的ThreadLocal快。
//static final ThreadLocal<InternalThreadLocalMap> slowThreadLocalMap = new ThreadLocal<InternalThreadLocalMap>();
//自增的索引值，默认从0开始。
//static final AtomicInteger nextIndex = new AtomicInteger()
//对象数组
//Object[] indexedVariables;
public final class InternalThreadLocalMap extends UnpaddedInternalThreadLocalMap {

    private static final InternalLogger logger = InternalLoggerFactory.getInstance(InternalThreadLocalMap.class);

    //默认数组容量大小
    private static final int DEFAULT_ARRAY_LIST_INITIAL_CAPACITY = 8;
    //stringBuilder的初始化值
    private static final int STRING_BUILDER_INITIAL_SIZE;
    //stringBuilder的最大值
    private static final int STRING_BUILDER_MAX_SIZE;
    //占位作用，表示未初始化
    public static final Object UNSET = new Object();

    private BitSet cleanerFlags;

    //一些初始化值的操作
    static {
        STRING_BUILDER_INITIAL_SIZE =
                SystemPropertyUtil.getInt("io.netty.threadLocalMap.stringBuilder.initialSize", 1024);
        logger.debug("-Dio.netty.threadLocalMap.stringBuilder.initialSize: {}", STRING_BUILDER_INITIAL_SIZE);

        STRING_BUILDER_MAX_SIZE = SystemPropertyUtil.getInt("io.netty.threadLocalMap.stringBuilder.maxSize", 1024 * 4);
        logger.debug("-Dio.netty.threadLocalMap.stringBuilder.maxSize: {}", STRING_BUILDER_MAX_SIZE);
    }

    //拿到线程A对应的InternalThreadLocalMap对象
    public static InternalThreadLocalMap getIfSet() {
        //获取当前线程，也就是线程A
        Thread thread = Thread.currentThread();
        //如果线程A是FastThreadLocalThread线程，直接返回内部的属性就行了。
        if (thread instanceof FastThreadLocalThread) {
            return ((FastThreadLocalThread) thread).threadLocalMap();
        }
        //此时说明是普通的线程，这个时候线程A就要从ThreadLocal里面拿属于自己的本地变量副本了。
        return slowThreadLocalMap.get();
    }

    public static InternalThreadLocalMap get() {
        //获取到当前线程-线程A
        Thread thread = Thread.currentThread();
        //根据线程A的类型走不同的逻辑
        if (thread instanceof FastThreadLocalThread) {
            //可以才去快速获取的策略，其实就是从线程A里面直接拿到InternalThreadLocalMap属性
            return fastGet((FastThreadLocalThread) thread);
        } else {
            //这个需要从InternalThreadLocalMap里面拿到静态的 slow...map 的属性里面拿到对应的InternalThreadLocalMap对象
            //注意，这里我可没说是线程A对应的InternalThreadLocalMap对象，，，
            return slowGet();
        }
    }

    //快速获取
    private static InternalThreadLocalMap fastGet(FastThreadLocalThread thread) {
        //拿到线程A对应的InternalThreadLocalMap对象
        InternalThreadLocalMap threadLocalMap = thread.threadLocalMap();
        //如果还没初始化，就初始化一下
        if (threadLocalMap == null) {
            thread.setThreadLocalMap(threadLocalMap = new InternalThreadLocalMap());
        }
        //已经初始化过直接返回即可。
        return threadLocalMap;
    }

    //低效获取
    private static InternalThreadLocalMap slowGet() {
        //获取UnpaddedInternalThreadLocalMap的静态属性，，，其实就是InternalThreadLocalMap的父类
        ThreadLocal<InternalThreadLocalMap> slowThreadLocalMap = UnpaddedInternalThreadLocalMap.slowThreadLocalMap;
        //从ThreadLocal里面来获取当前线程A对应的InternalThreadLocalMap对象
        InternalThreadLocalMap ret = slowThreadLocalMap.get();
        //尚未初始化
        if (ret == null) {
            //初始化
            ret = new InternalThreadLocalMap();
            //放到ThreadLocal里面
            slowThreadLocalMap.set(ret);
        }
        //返回线程A对应的InternalThreadLocalMap对象
        return ret;
    }

    //清理逻辑
    public static void remove() {
        //获取当前线程-线程A
        Thread thread = Thread.currentThread();
        //FastThreadLocalThread类型的线程
        if (thread instanceof FastThreadLocalThread) {
            //直接把里面的属性设置为空
            ((FastThreadLocalThread) thread).setThreadLocalMap(null);
        } else {
            //否则就调用ThreadLocal的remove方法。
            slowThreadLocalMap.remove();
        }
    }

    public static void destroy() {
        slowThreadLocalMap.remove();
    }

    //这里其实就是线程安全的自增，来获取下标
    public static int nextVariableIndex() {
        int index = nextIndex.getAndIncrement();
        if (index < 0) {
            nextIndex.decrementAndGet();
            throw new IllegalStateException("too many thread-local indexed variables");
        }
        return index;
    }

    public static int lastVariableIndex() {
        return nextIndex.get() - 1;
    }

    // Cache line padding (must be public)
    // With CompressedOops enabled, an instance of this class should occupy at least 128 bytes.
    public long rp1, rp2, rp3, rp4, rp5, rp6, rp7, rp8, rp9;

    private InternalThreadLocalMap() {
        super(newIndexedVariableTable());
    }

    //初始化对象数组，默认长度是8。
    private static Object[] newIndexedVariableTable() {
        Object[] array = new Object[32];
        Arrays.fill(array, UNSET);
        return array;
    }

    public int size() {
        int count = 0;

        if (futureListenerStackDepth != 0) {
            count ++;
        }
        if (localChannelReaderStackDepth != 0) {
            count ++;
        }
        if (handlerSharableCache != null) {
            count ++;
        }
        if (counterHashCode != null) {
            count ++;
        }
        if (random != null) {
            count ++;
        }
        if (typeParameterMatcherGetCache != null) {
            count ++;
        }
        if (typeParameterMatcherFindCache != null) {
            count ++;
        }
        if (stringBuilder != null) {
            count ++;
        }
        if (charsetEncoderCache != null) {
            count ++;
        }
        if (charsetDecoderCache != null) {
            count ++;
        }
        if (arrayList != null) {
            count ++;
        }

        for (Object o: indexedVariables) {
            if (o != UNSET) {
                count ++;
            }
        }

        // We should subtract 1 from the count because the first element in 'indexedVariables' is reserved
        // by 'FastThreadLocal' to keep the list of 'FastThreadLocal's to remove on 'FastThreadLocal.removeAll()'.
        return count - 1;
    }

    public StringBuilder stringBuilder() {
        StringBuilder sb = stringBuilder;
        if (sb == null) {
            return stringBuilder = new StringBuilder(STRING_BUILDER_INITIAL_SIZE);
        }
        if (sb.capacity() > STRING_BUILDER_MAX_SIZE) {
            sb.setLength(STRING_BUILDER_INITIAL_SIZE);
            sb.trimToSize();
        }
        sb.setLength(0);
        return sb;
    }

    public Map<Charset, CharsetEncoder> charsetEncoderCache() {
        Map<Charset, CharsetEncoder> cache = charsetEncoderCache;
        if (cache == null) {
            charsetEncoderCache = cache = new IdentityHashMap<Charset, CharsetEncoder>();
        }
        return cache;
    }

    public Map<Charset, CharsetDecoder> charsetDecoderCache() {
        Map<Charset, CharsetDecoder> cache = charsetDecoderCache;
        if (cache == null) {
            charsetDecoderCache = cache = new IdentityHashMap<Charset, CharsetDecoder>();
        }
        return cache;
    }

    public <E> ArrayList<E> arrayList() {
        return arrayList(DEFAULT_ARRAY_LIST_INITIAL_CAPACITY);
    }

    @SuppressWarnings("unchecked")
    public <E> ArrayList<E> arrayList(int minCapacity) {
        ArrayList<E> list = (ArrayList<E>) arrayList;
        if (list == null) {
            arrayList = new ArrayList<Object>(minCapacity);
            return (ArrayList<E>) arrayList;
        }
        list.clear();
        list.ensureCapacity(minCapacity);
        return list;
    }

    public int futureListenerStackDepth() {
        return futureListenerStackDepth;
    }

    public void setFutureListenerStackDepth(int futureListenerStackDepth) {
        this.futureListenerStackDepth = futureListenerStackDepth;
    }

    public ThreadLocalRandom random() {
        ThreadLocalRandom r = random;
        if (r == null) {
            random = r = new ThreadLocalRandom();
        }
        return r;
    }

    public Map<Class<?>, TypeParameterMatcher> typeParameterMatcherGetCache() {
        Map<Class<?>, TypeParameterMatcher> cache = typeParameterMatcherGetCache;
        if (cache == null) {
            typeParameterMatcherGetCache = cache = new IdentityHashMap<Class<?>, TypeParameterMatcher>();
        }
        return cache;
    }

    public Map<Class<?>, Map<String, TypeParameterMatcher>> typeParameterMatcherFindCache() {
        Map<Class<?>, Map<String, TypeParameterMatcher>> cache = typeParameterMatcherFindCache;
        if (cache == null) {
            typeParameterMatcherFindCache = cache = new IdentityHashMap<Class<?>, Map<String, TypeParameterMatcher>>();
        }
        return cache;
    }

    @Deprecated
    public IntegerHolder counterHashCode() {
        return counterHashCode;
    }

    @Deprecated
    public void setCounterHashCode(IntegerHolder counterHashCode) {
        this.counterHashCode = counterHashCode;
    }

    public Map<Class<?>, Boolean> handlerSharableCache() {
        Map<Class<?>, Boolean> cache = handlerSharableCache;
        if (cache == null) {
            // Start with small capacity to keep memory overhead as low as possible.
            handlerSharableCache = cache = new WeakHashMap<Class<?>, Boolean>(4);
        }
        return cache;
    }

    public int localChannelReaderStackDepth() {
        return localChannelReaderStackDepth;
    }

    public void setLocalChannelReaderStackDepth(int localChannelReaderStackDepth) {
        this.localChannelReaderStackDepth = localChannelReaderStackDepth;
    }

    public Object indexedVariable(int index) {
        Object[] lookup = indexedVariables;
        return index < lookup.length? lookup[index] : UNSET;
    }

    //将线程A调用FastThreadLocal对象set的值放到线程A对应的InternalThreadLocalMap的对象数组内。
    public boolean setIndexedVariable(int index, Object value) {
        //那到对象数组的引用
        Object[] lookup = indexedVariables;
        //判断下表是否越界
        //条件成立，说明此时没有越界，也就是FastThreadLocal的数量不是很多
        if (index < lookup.length) {
            //获取指定索引位置的旧值
            Object oldValue = lookup[index];
            //设置新的值
            lookup[index] = value;
            //返回是不是第一次设置
            return oldValue == UNSET;
        } else {
            //条件成立：下标越界，对象数组的容量不足了，需要扩容。
            expandIndexedVariableTableAndSet(index, value);
            return true;
        }
    }

    //扩容线程A对应的InternalThreadLocalMap对象内部的对象数组
    private void expandIndexedVariableTableAndSet(int index, Object value) {
        Object[] oldArray = indexedVariables;
        final int oldCapacity = oldArray.length;
        //计算新的对象数组的长度
        int newCapacity = index;
        newCapacity |= newCapacity >>>  1;
        newCapacity |= newCapacity >>>  2;
        newCapacity |= newCapacity >>>  4;
        newCapacity |= newCapacity >>>  8;
        newCapacity |= newCapacity >>> 16;
        newCapacity ++;
        //数据拷贝
        Object[] newArray = Arrays.copyOf(oldArray, newCapacity);
        Arrays.fill(newArray, oldCapacity, newArray.length, UNSET);
        //设置新的值到数组内
        newArray[index] = value;
        //数组替换
        indexedVariables = newArray;
    }

    //从线程A对应的map对象里面的对象数组里面移除当前FastThreadLocal对象对应的值。
    public Object removeIndexedVariable(int index) {
        //线程A对应的map对象里面的对象数组
        Object[] lookup = indexedVariables;
        //条件成立：说明下标未越界，可能设置过值
        if (index < lookup.length) {
            //获取一下
            Object v = lookup[index];
            //重置
            lookup[index] = UNSET;
            //返回旧的值，可能是UNSET。
            return v;
        } else {
            //下标越界说明根本就没设置过
            return UNSET;
        }
    }

    public boolean isIndexedVariableSet(int index) {
        Object[] lookup = indexedVariables;
        return index < lookup.length && lookup[index] != UNSET;
    }

    public boolean isCleanerFlagSet(int index) {
        return cleanerFlags != null && cleanerFlags.get(index);
    }

    public void setCleanerFlag(int index) {
        if (cleanerFlags == null) {
            cleanerFlags = new BitSet();
        }
        cleanerFlags.set(index);
    }
}
